﻿using UnityEditor;
using UnityEngine;

public static class ScriptingDefine
{
    public static void Define(string DefineStr)
    {
        SetPrecompile(new string[] { DefineStr }, true);
    }

    public static void Undefine(string DefineStr)
    {
        SetPrecompile(new string[] { DefineStr }, false);
    }

    /// <summary>
    /// 覆盖设置
    /// </summary>
    /// <param name="strMulty"></param>
    public static void SetAll(string strMulty)
    {
        PlayerSettings.SetScriptingDefineSymbolsForGroup(BuildTargetGroup.Android, strMulty);
        PlayerSettings.SetScriptingDefineSymbolsForGroup(BuildTargetGroup.iOS, strMulty);
        PlayerSettings.SetScriptingDefineSymbolsForGroup(BuildTargetGroup.Standalone, strMulty);
    }

    public static void SetPrecompile(string[] DefineStrs, bool isAdd)
    {
        SetPlatformDefine(BuildTargetGroup.Android, DefineStrs, isAdd);
        SetPlatformDefine(BuildTargetGroup.iOS, DefineStrs, isAdd);
        SetPlatformDefine(BuildTargetGroup.Standalone, DefineStrs, isAdd);
    }

    public static void SetPlatformDefine(BuildTargetGroup buildTargetGroup, string[] DefineStrs, bool isAdd)
    {
        string strDefineString = PlayerSettings.GetScriptingDefineSymbolsForGroup(buildTargetGroup);
        PresetPlatformDefine(ref strDefineString, DefineStrs, isAdd);
        PlayerSettings.SetScriptingDefineSymbolsForGroup(buildTargetGroup, strDefineString);
    }

    /// <summary>
    /// 写入多条时
    /// </summary>
    /// <param name="strDefineString"></param>
    /// <param name="DefineStr"></param>
    /// <param name="isAdd"></param>
    /// <returns></returns>
    public static void PresetPlatformDefine(ref string strDefineString, string[] DefineStrs, bool isAdd)
    {
        foreach (var DefineStr in DefineStrs)
        {
            if (string.IsNullOrEmpty(DefineStr))
            {
                Debug.LogError("预编译字符为无效!");
                continue;
            }

            if (isAdd)
            {
                if (strDefineString.IndexOf(DefineStr) < 0)
                {
                    if (strDefineString.LastIndexOf(";") < strDefineString.Length - 1)
                    {
                        strDefineString += ";";
                    }
                    strDefineString += DefineStr;
                }
            }
            else
            {
                strDefineString = strDefineString.Replace(DefineStr, "");
                strDefineString = strDefineString.Replace(";;", ";");
            }
        }
    }
}
